package fortunetelling.fortunetelling.listener;

import fortunetelling.fortunetelling.FortuneTelling;
import fortunetelling.fortunetelling.bean.Fortune;
import fortunetelling.fortunetelling.utils.FortuneConvertUtils;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @ClassName: PlayerInteractEventListener
 * @Date: 2020/10/5 0005 22:08
 * @Description:
 */
public class PlayerInteractEventListener implements Listener {
    @EventHandler
    public void playerInteractEvent(PlayerInteractEvent playerInteractEvent) {
        Player player = playerInteractEvent.getPlayer();
        ItemStack handingItem = playerInteractEvent.getItem();
        if (handingItem == null) {
            return;
        }
        ItemMeta itemMeta = handingItem.getItemMeta();
        if (itemMeta == null) {
            return;
        }
        if (!itemMeta.hasLore()) {
            return;
        }
        AtomicBoolean hasMyAttr = new AtomicBoolean(false);
        List<String> loreList = Optional.ofNullable(itemMeta.getLore()).orElse(new ArrayList<>());
        loreList.forEach(lore -> {
            if ("转运符".equals(lore)) {
                hasMyAttr.set(true);
            }
        });
        if (!hasMyAttr.get()) {
            return;
        }
        Fortune fortune = FortuneTelling.FORTUNE_TELLING_MAP.get(player.getName());
        if (fortune == null) {
            player.sendMessage("你还没有进行占卜，请输入/zhanbu 进行占卜");
            return;
        }
        if ("大吉".equals(fortune.getName())) {
            player.sendMessage("§a 您的运势己经是大吉了！");
            return;
        }
        player.getInventory().remove(handingItem);
        fortune = Optional.ofNullable(FortuneConvertUtils.translate("大吉")).orElse(new Fortune());
        FortuneTelling.FORTUNE_TELLING_MAP.put(player.getName(), fortune);
        player.sendMessage("§a 你的运势已经转为：" + fortune.getName() + " ！");
        player.sendMessage(fortune.getHint());
        player.sendMessage(fortune.getPoem());
    }
}
